package com.Glow.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Controller;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author Glow
 * @Date 2022-07-28 20:42:40
 * @Description 全局异常处理
 * @Version 1.0
 */
@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
//等价于@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * SQL异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
            log.error(ex.getMessage());
            //如果异常包含重复唯一主键
            if(ex.getMessage().contains("Duplicate entry"))
            {
                String[] split = ex.getMessage().split(" ");
                String msg = split[2]+"已存在";
                return R.error(msg);
            }else {

                return R.error("未知异常！");
            }
    }
    /**
     * 查看是否包含菜品和菜单抛出的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        //如果异常包含重复唯一主键
            return R.error(ex.getMessage());
    }
}
